package com.dlee.mvc.aop;

import java.lang.reflect.Method;

import com.dlee.mvc.container.BeanContainer;
import com.dlee.mvc.model.AspectMapping;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
 * 动态字节码增强,cglib.jar
 * @author d.lee
 * @date 2012-8-10
 */
public class CglibProxy implements MethodInterceptor
{

    private AspectMapping am;
    
    public Object createProxy(Object target,AspectMapping am)
    {
        this.am = am;
        Enhancer en = new Enhancer();
        en.setSuperclass (target.getClass ());
        en.setClassLoader (CglibProxy.class.getClassLoader ());
        en.setCallback (this);
        return en.create ();
    }
    
    @Override
    public Object intercept (Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable
    {
        System.out.println ("-----cglib增强-----");
        Object result = null;  
        try {  
            //在指定的方法上进行处理
            if(null != am.getAopMethod () && am.getAopMethod ().equals (method.getName ()))
            {
                if(null != am.getBeforeMethod () )
                {
                    Object aspect = BeanContainer.getBean (am.getBeanId ());
                    Method m = aspect.getClass ().getDeclaredMethod (am.getBeforeMethod (), new Class[]{});
                    m.invoke (aspect, new Object[]{});
                }
                result = proxy.invokeSuper(obj, args);  
                if(null != am.getAfterMethod ())
                {
                    Object aspect = BeanContainer.getBean (am.getBeanId ());
                    Method m = aspect.getClass ().getDeclaredMethod (am.getAfterMethod (), new Class[]{});
                    m.invoke (aspect, new Object[]{});
                }
            }
            else
            {
                result = proxy.invokeSuper(obj, args); 
            }
        } catch (Exception e) {  
        }finally{  
        }  
        return result; 
    }

}
